﻿#include "mytableview.h"
#include "product.h"

MyTableView::MyTableView(QWidget *parent) : QTableView(parent)
{
    setSelectionBehavior(QAbstractItemView::SelectRows);
}

MyTableView::~MyTableView(){
    if(!key.isEmpty()){
        Product::setHiddenStateList(key, hiddenStateList);
    }

    for(int i=0;i<keyList.size();i++){
        QString curKey = keyList[i];
        if(!curKey.isEmpty()){
            Product::setHiddenStateList(curKey, multiHiddenStateList[i]);
        }
    }
}

void MyTableView::setListPushButtonAndMenuLabel(ListPushButton *listPushButton, QStringList menuLabel){
    this->listPushButton = listPushButton;
    listPushButton->setMenuItemsLabel(menuLabel);

    connect(listPushButton, &ListPushButton::menuItemClicked,
            [=](int index, bool checked)
    {
        this->setColumnHidden(index, !checked);
        this->hiddenStateList[index] = checked;
    });
}

void MyTableView::setMultiListPushButton(MultiListPushButton *multiListPushButton){
    this->multiListPushButton = multiListPushButton;
    keyList.clear();
    multiHiddenStateList.clear();

    connect(multiListPushButton, &MultiListPushButton::menuItemClicked,
            [=](int index, bool checked){
        this->setColumnHidden(index, !checked);
        multiHiddenStateList[multiListPushButton->getCurrentMenuIndex()][index] = checked;
    });
}

void MyTableView::addMultiMenu(QString key, QStringList menuLabel){
    keyList.append(key);
    multiListPushButton->addMenuItemsLabel(menuLabel);
}

void MyTableView::initHiddenStateList(QString key, int size){
    this->key = key;
    hiddenStateList = Product::getHiddenStateList(key);
    if(hiddenStateList.size() != size){
        hiddenStateList.clear();
        for(int i=0;i<size;i++){
            hiddenStateList<<true;
        }
    }

    listPushButton->setCheckedState(hiddenStateList);
    refreshHiddenState();
}

void MyTableView::initMultiHiddenStateList(){
    for(int i=0;i<keyList.size();i++){
        QString curKey = keyList[i];
        QList<bool> curHiddenStateList = Product::getHiddenStateList(curKey);
        int curMenuSize = multiListPushButton->getMenuSize(i);
        if(curHiddenStateList.size() != curMenuSize){
            curHiddenStateList.clear();
            for(int i=0;i<curMenuSize;i++){
                curHiddenStateList<<true;
            }
        }
        multiHiddenStateList.append(curHiddenStateList);
    }

    multiListPushButton->setCheckedState(multiHiddenStateList);
    refreshMultiHiddenState();
}

void MyTableView::refreshHiddenState(){
    for(int i=0;i<hiddenStateList.size();i++){
        setColumnHidden(i, !hiddenStateList[i]);
    }
}

void MyTableView::refreshMultiHiddenState(){
    QList<bool> curHiddenStateList = multiHiddenStateList[multiListPushButton->getCurrentMenuIndex()];
    for(int i=0;i<curHiddenStateList.size();i++){
        setColumnHidden(i, !curHiddenStateList[i]);
    }
}
